<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { useRoute } from 'vue-router';
import { GetStoryDetail, type StoryItem } from '../api/story';
import DOMPurify from 'isomorphic-dompurify';

const story = ref<StoryItem | null>(null);
const isPlaying = ref(false);
const progress = ref(0);
const audio = ref<HTMLAudioElement | null>(null);
const isCollected = ref(false);

const fetchStoryDetail = async (id: number) => {
  try {
    const response = await GetStoryDetail(id);
    story.value = response.data.data;
  } catch (error) {
    console.error('获取故事详情失败:', error);
  }
};

const togglePlay = () => {
  if (!audio.value || !story.value?.ttsUrl) return;
  
  if (isPlaying.value) {
    audio.value.pause();
  } else {
    audio.value.play();
  }
  isPlaying.value = !isPlaying.value;
};

const toggleCollect = () => {
  // TODO: 实现收藏功能的API调用
  isCollected.value = !isCollected.value;
};

const updateProgress = () => {
  if (!audio.value) return;
  progress.value = (audio.value.currentTime / audio.value.duration) * 100;
};

const setProgress = (event: MouseEvent) => {
  if (!audio.value) return;
  const progressBar = event.currentTarget as HTMLElement;
  const rect = progressBar.getBoundingClientRect();
  const percent = (event.clientX - rect.left) / rect.width;
  progress.value = percent * 100;
  audio.value.currentTime = percent * audio.value.duration;
};

onMounted(() => {
  const route = useRoute();
  const storyId = Number(route.params.id);
  audio.value = new Audio();
  
  audio.value.addEventListener('timeupdate', updateProgress);
  audio.value.addEventListener('ended', () => {
    isPlaying.value = false;
    progress.value = 0;
  });

  fetchStoryDetail(storyId).then(() => {
    if (story.value?.ttsUrl) {
      audio.value!.src = story.value.ttsUrl;
      audio.value!.load();
    }
  });
});

onBeforeUnmount(() => {
  if (audio.value) {
    audio.value.pause();
    audio.value.removeEventListener('timeupdate', updateProgress);
    audio.value.removeEventListener('ended', () => {
      isPlaying.value = false;
      progress.value = 0;
    });
    audio.value.src = '';
    audio.value = null;
  }
  isPlaying.value = false;
  progress.value = 0;
});
</script>

<template>
  <div class="container mx-auto pt-2">
    <div v-if="story" class="bg-white/80 backdrop-blur-md rounded-2xl p-6 shadow-lg">
      <!-- 故事标题和封面 -->
      <div class="mb-8 relative">
        <div class="record-player-container relative">
          <img :src="story.thumbnail" :alt="story.name" class="w-full h-64 object-cover rounded-full shadow-xl transition-transform duration-500" :class="{ 'spinning': isPlaying }">
          <div class="record-arm absolute top-0 right-0 w-24 h-12 origin-right transform -rotate-45 transition-transform hover:rotate-0">
            <div class="absolute right-0 bottom-0 w-4 h-4 bg-gray-800 rounded-full"></div>
          </div>
        </div>
        <h1 class="text-2xl font-bold text-purple-600 mt-6">{{ story.name }}</h1>
        <p class="text-gray-500">{{ story.title }}</p>
      </div>

      <!-- 播放器控制区域 -->
      <div class="mb-8 bg-purple-50 rounded-xl p-4">
        <!-- 进度条 -->
        <div class="relative h-2 bg-purple-200 rounded-full mb-4 cursor-pointer" @click="setProgress">
          <div class="absolute h-full bg-purple-600 rounded-full" :style="{ width: `${progress}%` }"></div>
        </div>

        <!-- 控制按钮 -->
        <div class="flex items-center justify-between">
          <div class="flex items-center space-x-4">
            <button @click="togglePlay" class="p-3 bg-purple-600 rounded-full hover:bg-purple-700 transition-colors">
              <img v-if="isPlaying" src="https://unpkg.com/lucide-static@latest/icons/pause.svg" class="w-6 h-6 text-white" alt="暂停">
              <img v-else src="https://unpkg.com/lucide-static@latest/icons/play.svg" class="w-6 h-6 text-white" alt="播放">
            </button>
          </div>
          <div class="flex items-center space-x-4">
            <button @click="toggleCollect" class="p-3 bg-white rounded-full hover:bg-purple-100 transition-colors">
              <img v-if="isCollected" src="https://unpkg.com/lucide-static@latest/icons/heart-fill.svg" class="w-6 h-6 text-red-500 text-xs" alt="已收藏">
              <img v-else src="https://unpkg.com/lucide-static@latest/icons/heart.svg" class="w-6 h-6 text-gray-500 text-xs" alt="收藏">
            </button>
          </div>
        </div>

        <!-- 统计信息 -->
        <div class="text-sm text-gray-500 mt-4 text-center text-right">
          <span>浏览: {{ story.views }}</span>
          <span class="mx-2">|</span>
          <span>收藏: {{ story.collects }}</span>
        </div>
      </div>

      <!-- 故事内容 -->
      <div class="prose prose-purple max-w-none text-xs" v-html="DOMPurify.sanitize(story.content)"></div>
    </div>
  </div>
</template>

<style scoped>
.prose {
  font-size: 0.9rem;
  line-height: 1.8;
}

:deep(.prose p) {
  text-indent: 2em;
  margin-bottom: 1em;
  letter-spacing: 0.05em;
  text-align: left;
}

.record-player-container {
  width: 256px;
  height: 256px;
  margin: 0 auto;
  background: linear-gradient(45deg, #2c2c2c, #3a3a3a);
  border-radius: 50%;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  overflow: hidden;
}

.record-player-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.record-arm {
  transition: all 0.3s ease;
}

.record-player-container img.spinning {
  animation: spin 20s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>